var hx = require("hbuilderx");

const BaiduTranslate = require('node-baidu-translate')

const tencentcloud = require('tencentcloud-sdk-nodejs')
const TmtClient = tencentcloud.tmt.v20180321.Client

const CryptoJS = require('crypto-js')
const axios = require('axios')

// 获取配置的密钥
function getSecret(type) {
	const [appid, secret] = hx.workspace.getConfiguration('varTranslation').get(type).split(',')
	if (!(appid && secret)) {
		hx.window.showInformationMessage(`${type}翻译未配置,请现在设置中配置`)
		return []
	}
	return [appid, secret]
}
// 确保只有一个实例
function createSingletonInstance(constructor, ...args) {
	if (!constructor.instance) {
		constructor.instance = new constructor(...args)
	}
	return constructor.instance
}

// 百度翻译
async function baidu(text, language) {
	const [appid, secretKey] = getSecret('baidu')
	if (!appid || !secretKey) return
	const baiduInstance = createSingletonInstance(BaiduTranslate, appid, secretKey)
	const res = await baiduInstance.translate(text, language)
	return res.trans_result[0].dst
}

// 腾讯翻译
async function tencent(text, language) {
	const [SecretId, SecretKey] = getSecret('tencent')
	if (!appid || !secretKey) return
	const clientConfig = {
		credential: {
			secretId: SecretId,
			secretKey: SecretKey,
		},
		region: 'ap-chongqing',
		profile: {
			httpProfile: {
				endpoint: 'tmt.tencentcloudapi.com',
			},
		},
	}
	const tencentInstance = createSingletonInstance(TmtClient, clientConfig)
	const params = {
		SourceText: text,
		Source: 'auto',
		Target: language,
		ProjectId: 0,
	}
	const res = await tencentInstance.TextTranslate(params)
	return res.TargetText
}

// 有道翻译
async function youdao(text, language) {
	const [appKey, key] = getSecret('youdao')
	if (!appid || !secretKey) return
	const salt = new Date().getTime()
	const curtime = Math.round(new Date().getTime() / 1000)
	const str1 = appKey + truncate(text) + salt + curtime + key
	const sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex)
	const data = {
		q: text,
		appKey: appKey,
		salt: salt,
		from: 'auto',
		to: language,
		sign: sign,
		signType: 'v3',
		curtime: curtime,
	}
	const res = await axios.get('https://openapi.youdao.com/api', {
		params: data,
	})
	return res.data.translation[0]
}

function truncate(q) {
	const len = q.length
	if (len <= 20) return q
	return q.substring(0, 10) + len + q.substring(len - 10, len)
}


const engines = {
	baidu,
	tencent,
	youdao,
}
module.exports = engines